package com.lj.cloudDisk.controller;

import com.lj.cloudDisk.utils.R;
import com.lj.cloudDisk.utils.SMSUtils;
import com.lj.cloudDisk.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * 验证码操作
 */
@RequestMapping("/validateCode")
@RestController
@Api(value = "发送短信接口")
@Slf4j
public class validateCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    //发送验证码
    @ApiOperation(value = "发送短信")
    @GetMapping("/sendSMS/{phone}")
    public R sendSMS(@PathVariable String phone){

            //随机生成数字验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        log.debug("手机号:{},验证码:{}",phone,validateCode);
            //给用户发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,phone,validateCode.toString());
        } catch (Exception e) {
            e.printStackTrace();
                 return R.error().message("短信发送失败");
        }

        //将验证码保存到redis(1分钟)
          redisTemplate.opsForValue().set(phone,validateCode.toString(),1, TimeUnit.MINUTES);
        return  R.success().message("短信发送成功");

    }


}
